<template>
    <div>
        <div class="r-header">
            <div class="header-item">
                <span>时间：</span>
                <!-- <el-date-picker size="small" v-model="daysdate" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker> -->
                <el-date-picker size="small" v-model="daysdate" type="month" value-format="yyyy-MM" format="yyyy-MM" placeholder="选择日期">
                </el-date-picker>
            </div>
            <div class="header-item">
                <span>监测项目：</span>
                <el-select size="small" v-model="bussinessData" multiple collapse-tags style="margin-left: 20px;"
                    placeholder="请选择" @change="selectChange">
                    <el-option v-for="item in bussinessItemList" :key="item.itemCode" :label="item.itemName"
                        :value="item.itemCode">
                    </el-option>
                </el-select>
            </div>
            <div class="header-item">
                <span>是否超标：</span>
                <el-switch v-model="isOver" active-color="#13ce66" inactive-color="#dddddd">
                </el-switch>
            </div>

        </div>
        <div class="header-btns">
            <el-button class="query-btn" type="primary" icon="el-icon-search" size="mini"
                @click="handleQuery">查询</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            <!-- <el-button type="warning" icon="el-icon-download" size="mini" plain
                v-hasPermi="['system:user:export']">导出</el-button> -->
        </div>
        <div class="content">
            <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%">
                <el-table-column label="序号">
                    <template slot-scope="scope">{{ scope.$index + 1 }}</template>
                </el-table-column>
                <el-table-column label="断面名称">
                    <template slot-scope="scope">{{ scope.row.SegmentName }}</template>
                </el-table-column>
                <el-table-column prop="RiverName" label="所属河流/湖库" width="120">
                </el-table-column>
                <el-table-column prop="SampleDate" label="监测时间" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="segmentIndex" label="水质指数" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="Level" label="水质级别" show-overflow-tooltip>
                </el-table-column>
                <el-table-column label="是否超标" show-overflow-tooltip>
                    <template slot-scope="scope">{{ scope.row.IsOvers == 0 ? '达标' : '超标' }}</template>
                </el-table-column>
                <el-table-column prop="waterQuality" label="水质评价" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="evaluationTrend" label="水质变化趋势" show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="PollutionItem" label="超标描述" show-overflow-tooltip></el-table-column>
                <el-table-column prop="dataSource" label="数据来源" show-overflow-tooltip></el-table-column>
                <el-table-column v-for="(item, index) in businessList" :key="index" :label="item.itemNameUnit" show-overflow-tooltip>
                    <template slot-scope="scope">{{scope.row[item.itemCode + '_Val'] }}</template>
                </el-table-column>
            </el-table>
            
            <!-- 分页组件 -->
            <div class="pagination-container" style="margin-top: 10px;">
                <el-pagination
                    background
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    :current-page="currentPage"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="pageSize"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </div>
    </div>
</template>
<script>
import { bussinessItemData, manualMonitorData, manualMonitordataLastTime } from '@/api/dataResources/waterJcData/sgMonitor'
export default {
    name: 'rightTable',
    props: {
        checkedTreeNodes: {
            type: Array,
            default: () => []
        }
    },
    data() {
        return {
            originDate: '',
            daysdate: '',
            beginTime: '',
            endTime: '',
            isOver: false,
            bussinessItemList: [],
            bussinessData: '',
            tableData: [],
            businessList: [],
            // 分页相关参数
            currentPage: 1,
            pageSize: 10,
            total: 0,
        }

    },
    created() {
        this.query();
    },
    methods: {
        async manualMonitordataLastTime() {
            try {
                const res = await manualMonitordataLastTime()
                if (res.code == 200) {
                    this.originDate = res.data.dataTime || new Date();
                    this.daysdate = this.originDate;
                }
            } catch (error) {
                console.error('Error fetching last time data:', error)
            }
        },
        selectedItems() {
            return this.bussinessData.map((itemCode) => {
                const item = this.bussinessItemList.find(
                    (option) => option.itemCode === itemCode);
                return item
            });
        },
        
        // 递归函数，找出所有最底层的子节点
        findBottomLevelNodes(nodes) {
            let bottomNodes = [];
            
            // 递归处理节点
            const findBottomNodes = (nodeList) => {
                nodeList.forEach(node => {
                    // 检查节点是否有子节点且子节点长度大于0
                    if (node.children && node.children.length > 0) {
                        // 有子节点，继续递归查找
                        findBottomNodes(node.children);
                    } else {
                        // 没有子节点或子节点长度为0，这是最底层节点
                        bottomNodes.push(node);
                    }
                });
            };
            
            findBottomNodes(nodes);
            return bottomNodes;
        },
        selectChange() {
            // this.businessList = this.selectedItems();
            // console.log(">>>", this.businessList);
            this.handleQuery();
        },
        getParams() {
            this.businessList = this.selectedItems();
            let params = {
                pageNum: this.currentPage,
                pageSize: this.pageSize,
                beginTime: this.daysdate,
                endTime: this.daysdate,
                isOver: this.isOver ? 1 : 2,
                "bussinessCategoryCode": "CBN",
            }            
            // 获取所有最底层的节点
            const bottomNodes = this.findBottomLevelNodes(this.checkedTreeNodes);
            const targetNodes = bottomNodes.length > 0 ? bottomNodes : [];
            let nodeIds = targetNodes.map(node => node.id);
            nodeIds = [...new Set(nodeIds)];
            // 提取节点ID
            params.segmentId = nodeIds.join(',');
            params.itemCode = this.bussinessData.join(',')
            return params;
        },
        resetQuery() {
            this.bussinessData =  this.bussinessItemList.map(item => item.itemCode)
            this.daysdate = this.originDate
            this.handleQuery()
        },
        handleQuery() {
            let params = this.getParams();
            console.log('params', params)
            manualMonitorData(params).then(res => {
                if (res.code == 200) {
                    // 假设返回的数据结构包含list和total
                    // 如果API返回的直接是列表，则使用下面的注释代码
                    // this.tableData = res.data
                    // this.total = res.data.length
                    
                    // 如果API返回的是分页数据，包含list和total字段
                    this.tableData = res.rows;
                    this.total = res.total;
                }
            })
        },
        
        // 分页处理方法
        handleSizeChange(val) {
            this.pageSize = val;
            this.handleQuery();
        },
        
        handleCurrentChange(val) {
            this.currentPage = val;
            this.handleQuery();
        },
        changeSwitch(val) {
            this.isOver = val;
        },
        changeDate(val) {
            this.beginTime = this.parseTime(val[0], '{yyyy}-{mm}-{dd}')
            this.endTime = this.parseTime(val[1], '{yyyy}-{mm}-{dd}')
        },
        async query() {
            await this.manualMonitordataLastTime()
            await this.getBussinessItemData()
            await this.handleQuery()
        },
        async getBussinessItemData() {
            try {
                const res = await bussinessItemData({ bussinessCategoryCode: 'CBN' })
                if (res.code == 200) {
                    this.bussinessItemList = res.data;
                    this.bussinessData =  this.bussinessItemList.map(item => item.itemCode)
                }
            } catch (error) {
                console.error('Error fetching business items:', error)
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.r-header {
    display: flex;
    justify-content: left;
    align-items: center;
}

.header-item {
    margin-right: 10px;
}

.header-btns {
    display: flex;
    margin-top: 10px;
}

.content {
    margin-top: 10px;

}
</style>